package com.ruoyi.monitor.controller;

import java.util.*;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.monitor.Vo.CityVo;
import com.ruoyi.monitor.domain.PollutantAvg;
import com.ruoyi.monitor.service.IPolluantAvgService;
import com.ruoyi.monitor.utils.APICenter;
import com.ruoyi.monitor.utils.Common.Constant;
import org.apache.log4j.Logger;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.monitor.domain.Pollutant;
import com.ruoyi.monitor.service.IPollutantService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 污染物Controller
 * 
 * @author xzx
 * @date 2023-01-04
 */
@RestController
@RequestMapping("/monitor/pollutant")
public class PollutantController extends BaseController
{
    @Autowired
    private IPollutantService pollutantService;
    @Autowired
    private IPolluantAvgService polluantAvgService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private APICenter apiCenter;
    private static Logger logger = Logger.getLogger(PollutantController.class);

    /**
     * 统计每月不同等级的天数
     * @param date
     * @return
     */
    @PostMapping("/quality/days")
    public HashMap<Integer, Integer> daysOfQuality(@RequestBody String date){
        System.out.println(date);
        Map<String, Object> totalDays = redisCache.getCacheMap("totalDays");
        System.out.println(totalDays);
        HashMap<Integer, Integer> res = null;
        if (totalDays.size()==0){
            logger.warn("重新获取全部组成");
            TreeMap<String, HashMap<Integer, Integer>> qualities = polluantAvgService.daysOfQualities(false);
            TreeMap<String, HashMap<Integer, Integer>> year = polluantAvgService.daysOfQualities(true);
            qualities.putAll(year);
            res = qualities.get(date);
            redisCache.setCacheMap("totalDays",qualities);
            redisCache.expire("totalDays",30, TimeUnit.MINUTES);
        }else {
            Object o = totalDays.get(date);
            res = (HashMap<Integer, Integer>) o;
        }
        logger.info(res);
        return res;
    }

    @GetMapping("/city/rank")
    public AjaxResult rank(){
        logger.info("--------获取排行榜-------");
        List<CityVo>  cityVoList = redisCache.getCacheList("rank");
        if (cityVoList.size()==0){
            logger.warn("重新获取排行榜中");
            cityVoList = apiCenter.getRankData();
            logger.info("排行榜数据"+cityVoList);
            if (cityVoList.size()==0) logger.warn("没有排行数据");
            else {
                redisCache.setCacheList("rank",cityVoList);
                redisCache.expire("rank",30, TimeUnit.MINUTES);
            }
        }
        else logger.info("排行榜数据"+cityVoList);
        return success(cityVoList);
    }
    @GetMapping("/city/rank/nowcity")
    public AjaxResult city(){
        CityVo res = null;
        logger.info("--------当地数据-------");
        List<CityVo>  cityVoList= redisCache.getCacheList("rank");
        if (cityVoList.size()==0){
            cityVoList = apiCenter.getRankData();
            if (cityVoList.size()==0) logger.warn("没有排行数据");
            else {
                for (CityVo c:cityVoList) {
                    if (Constant.city.equals(c.getArea())){
                        res = c;
                        break;
                    }
                }
            }
        }
        else {
            for (CityVo c:cityVoList) {
                if (Constant.city.equals(c.getArea())){
                    res = c;
                    break;
                }
            }
        };
        return success(res);
    }

    @GetMapping("/bar/days")
    public AjaxResult daysOfTypes(){
        logger.info("获取每月组成");
        TreeMap<String, HashMap<Integer, Integer>> map = polluantAvgService.daysOfQualities(false);
        logger.info(map);

        return success(map);
    }

    @GetMapping("/all")
    public AjaxResult allByDay(){
        List<PollutantAvg> pollutantAvgs = polluantAvgService.selectAllByDay();

        return success(pollutantAvgs);
    }


    /**
     * 周、月、年折线图
     * @return
     */
    @GetMapping("/cycle/{type}")
    public AjaxResult cycleData(@PathVariable("type")Integer type){
        List<PollutantAvg> cache = redisCache.getCacheList("cycle"+type);
        if (cache.size() == 0){
            Set<PollutantAvg> pollutantAvgs = polluantAvgService.selectAVGByType(type);
            cache.addAll(pollutantAvgs);
            redisCache.setCacheList("cycle"+type,cache);
            redisCache.expire("cycle"+type,30, TimeUnit.MINUTES);
            System.out.println("-----周期初始化-----");
            cache.forEach(pollutantAvg -> System.out.println(pollutantAvg));
            System.out.println("------------------");
        }

        return success(cache);
    }

    /**
     * aqi柱形图周数据
     * @return
     */
    @GetMapping("/aqiBar/{days}")
    public AjaxResult aqiBar(@PathVariable("days")Integer days){
        if (ObjectUtil.isEmpty(days)) days=31;
        List<PollutantAvg> list = redisCache.getCacheList("his"+days);
        if (list.size() == 0   ) {
            redisCache.deleteObject("his"+days);
             list = polluantAvgService.selectDaySingle(new Date(),days);
            redisCache.setCacheList("his"+days, list);
            redisCache.expire("his"+days,30, TimeUnit.MINUTES);
            System.out.println("---------柱形图初始化----------");
            System.out.println("查询获取：" + list);
            System.out.println("---------" + new Date() + "---------");
        }else {
            System.out.println(list.get(list.size()-1));
            Date last = list.get(list.size() - 1).getCt();
            int between = new Date().getDate()-last.getDate();
            if (between >= 1){
                redisCache.deleteObject("his"+days);
                list = polluantAvgService.selectDaySingle(new Date(),days);
                redisCache.setCacheList("his"+days, list);
                redisCache.expire("his"+days,30, TimeUnit.MINUTES);
                System.out.println("---------柱形图初始化----------");
                System.out.println("查询获取：" + list);
                System.out.println("---------" + new Date() + "---------");
            }
        }
        return success(list);
    }

    /**
     * 仪表盘
     * 实时数据
     * @return
     */

    @GetMapping("/aqi")
    public AjaxResult AQI(){
        System.out.println("------aqi获取------");
        return success(pollutantService.selectLatestPollutant());
    }

    /**
     * 雷达图
     * 日，周，月数据
     * @return
     */
    @GetMapping("/radar")
    public TableDataInfo radar() {
        List<PollutantAvg> list = redisCache.getCacheList("radar");
        if (list.size() == 0) {
           PollutantAvg data30 = polluantAvgService.selectDaysAVG(new Date(), 30);
            PollutantAvg data7 = polluantAvgService.selectDaysAVG(new Date(), 7);
            PollutantAvg today = polluantAvgService.selectDaysAVG(new Date(), 0);
            list.add(today);
            list.add(data7);
            list.add(data30);
            redisCache.setCacheList("radar", list);
            redisCache.expire("radar",30,TimeUnit.MINUTES);
            System.out.println("---------雷达图初始化----------");
            System.out.println("查询获取：" + list);
            System.out.println("---------" + new Date() + "---------");
        }
        return getDataTable(list);

    }


    /**
     * 获取24小时内的数据
     */
    @PreAuthorize("@ss.hasPermi('air:pollutant:list')")
    @GetMapping("/list")
    public TableDataInfo list()
    {
        List<Pollutant> pollutantList = redisCache.getCacheList("pollutantList");
        List<Pollutant> list = JSON.parseArray(JSON.toJSONString(pollutantList), Pollutant.class);
        if (list.size()==0){
            Pollutant latestPollutant = pollutantService.selectLatestPollutant();
            if (!ObjectUtil.isEmpty(latestPollutant)) {
                long between = DateUtil.between(latestPollutant.getCt(), new Date(), DateUnit.HOUR);
                if (between>=1){
                    System.out.println("****获取实时数据****");
                    apiCenter.saveData();
                }
            }
            list = pollutantService.selectPollutantList();
            //如果数据不是最新的还要获取一次api
            redisCache.setCacheList("pollutantList",list);
            redisCache.expire("pollutantList",30,TimeUnit.MINUTES);
            System.out.println("---------折线图初始化----------");
            System.out.println("查询获取："+list);
            System.out.println("---------"+new Date()+"---------");
        }else {
            Date last = list.get(0).getCt();
            System.out.println(list);
            long between = DateUtil.between(last, new Date(), DateUnit.HOUR);
            System.out.println("时间差:"+between);
            if (between>=1){
                apiCenter.saveData();
                redisCache.deleteObject("pollutantList");
                list = pollutantService.selectPollutantList();
                redisCache.setCacheList("pollutantList",list);
                redisCache.expire("pollutantList",30,TimeUnit.MINUTES);
            }
        }
        return getDataTable(list);
    }

    /**
     * 查询【请填写功能名称】列表
     */
    @PreAuthorize("@ss.hasPermi('air:pollutant:listAll')")
    @GetMapping("/listAll")
    public TableDataInfo allList(Pollutant hourPollutant)
    {
        startPage();
        List<Pollutant> list = pollutantService.selectPollutantListCondition(hourPollutant);
        return getDataTable(list);
    }

    /**
     * 导出污染物列表
     */
    @PreAuthorize("@ss.hasPermi('air:pollutant:export')")
    @Log(title = "污染物", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Pollutant pollutant)
    {
        List<Pollutant> list = pollutantService.selectPollutantListCondition(pollutant);
        ExcelUtil<Pollutant> util = new ExcelUtil<Pollutant>(Pollutant.class);
        util.exportExcel(response, list, "污染物数据");
    }

    /**
     * 新增污染物
     */
    @PreAuthorize("@ss.hasPermi('air:pollutant:add')")
    @Log(title = "污染物", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Pollutant pollutant)
    {
        return toAjax(pollutantService.insertPollutant(pollutant));
    }

    /**
     * 修改
     */
    @PreAuthorize("@ss.hasPermi('air:pollutant:edit')")
    @Log(title = "修改", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Pollutant hourPollutant)
    {
        return toAjax(pollutantService.saveOrUpdate(hourPollutant));
    }

    /**
     * 删除
     */
    @PreAuthorize("@ss.hasPermi('air:pollutant:remove')")
    @Log(title = "删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(pollutantService.removeByIds(Arrays.asList(ids)));
    }

    /**
     * 获取【请填写功能名称】详细信息
     */
    @PreAuthorize("@ss.hasPermi('air:pollutant:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(pollutantService.getById(id));
    }





}
